<template>
  <div class="avatar-uploader">
    <!--
      action 必传的属性 提供一个后端接口地址, 如果你不希望提供一个固定的后端地址
        此时可以给action ''或者'#'

        auto-upload 是否在选取文件后立即进行上传
        默认为true    立即进行上传
        不希望进行上传  ->false
    -->
    <el-upload
      action="#"
      list-type="picture-card"
      :http-request="handleUpload"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :limit="limit"
      :class="{ disabled: isDisabled }"
      :before-upload="handleBeforeUpload"
    >
      <span>上传图片</span>
      <i class="el-icon-circle-close" />
    </el-upload>
    <el-dialog title="预览" :visible="isShow" @close="isShow = false">
      <div style="text-align: center">
        <img :src="imgUrl" alt="" style="width;:100% " />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)

const cos = new COS({
  SecretId: 'AKID2tVsynMfhSw96l9G7h5C3dwzkFTQ6WfW', // 身份识别ID
  SecretKey: 'bw0nJaiZhZBWaNu97oDLCm47tOdcKktl' // 身份秘钥
})
export default {
  name: 'UploadImage',
  props: {
    limit: {
      type: Number,
      default: 1
    },

    // 数据回显的父传子过来的地址
    img: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imgUrl: '',
      isShow: false,
      fileList: []
    }
  },
  // 数据回显时--监听img的变化:如果有变化,就添加到fileList数组
  watch: {
    img(newValue) {
      if (newValue) {
        // this.fileList.push({
        //   url: this.img
        // })
        // 优化:
        this.fileList = [{ url: this.img }]
      } else {
        this.fileList = []
      }
    }
  },
  computed: {
    isDisabled() {
      return this.fileList.length >= this.limit
    },
    isAllUploadSuccess() {
      return this.fileList.every((item) => item.status === 'success')
    }
  },
  methods: {
    // 校验
    handleBeforeUpload(file) {
      // file => 添加的文件对象
      // console.log(file)
      // this.$message.error('你错了!')
      // return false

      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }

      return true
    },

    // 预览
    handlePreview(file) {
      this.isShow = true
      console.log(file)
      this.imgUrl = file.url
    },
    // 删除
    handleRemove(file, fileList) {
      this.fileList = [...fileList]
    },
    // 上传
    handleUpload(obj) {
      const uid = obj.file.uid
      const fileObj = this.fileList.find((item) => item.uid === uid)
      fileObj.status = 'uploading'
      cos.putObject(
        {
          Bucket: 'penny-1313132910' /* 填入自己的存储桶，必须字段 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: 'hrsass-99-' + parseInt(Math.random() * 99999) + obj.file.name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          StorageClass: 'STANDARD', // 设置对象存储类型: 标准
          Body: obj.file, // 上传的文件对象
          onProgress: (progressData) => {
            fileObj.percentage = parseInt(progressData.percent * 100)
          }
        },
        (err, data) => {
          // 注意使用箭头函数,避免this问题(this => 组件)
          // 成功或者失败走这里
          // console.log(this)
          // console.log(err || data)
          if (err) return console.log('上传失败', err)

          // 更新数据!
          fileObj.url = 'https://' + data.Location

          this.$emit('changeImg', fileObj.url)
          setTimeout(() => {
            fileObj.status = 'success'
          }, 1000)
        }
      )
    },
    // 同步
    handleChange(file, fileList) {
      this.fileList = [...fileList]
      // console.log(file)
    }
  }
}
</script>
<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
.avatar-uploader {
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
  margin-left: 4px;
  i {
    position: absolute;
    right: 0;
    top: 0;
    transform: translate(50%, -50%);
    background: #fff;
    font-size: 18px;
    color: #999;
  }
  ::v-deep {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      width: 100px;
      height: 60px;
      line-height: 60px;
    }
    .el-upload-list__item {
      width: 100px;
      height: 60px;
      border: 0;
      margin: 0;
    }
  }
  el-upload {
    display: inline-block;
    text-align: center;
    cursor: pointer;
    outline: 0;
  }
}
</style>